package es.manuel.maa.bean;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.validation.constraints.Size;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

import es.manuel.maa.dto.MenuOption;
import es.manuel.maa.model.User;
import es.manuel.maa.service.UserService;
import es.manuel.maa.service.impl.UserServiceImpl;
import es.manuel.maa.util.JSFUtil;

@ManagedBean(name = RegisterUserBean.ID)
@RequestScoped
public class RegisterUserBean {

	private static final Log log = LogFactory.getLog(RegisterUserBean.class);

	public static final String ID = "registerUserBean";

	@NotEmpty
	@Size(min = 8, max = 16)
	private String username;

	@NotEmpty
	private String name;

	@NotEmpty
	private String firstSurname;

	private String secondSurname;

	@NotEmpty
	@Email
	private String email;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getFirstSurname() {
		return firstSurname;
	}

	public void setFirstSurname(String firstSurname) {
		this.firstSurname = firstSurname;
	}

	public String getSecondSurname() {
		return secondSurname;
	}

	public void setSecondSurname(String secondSurname) {
		this.secondSurname = secondSurname;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String registerUser() {
		try {
			User usuario = new User();
			usuario.setUsername(this.username);
			usuario.setName(this.name);
			usuario.setFirstSurname(this.firstSurname);
			usuario.setSecondSurname(this.secondSurname);
			usuario.setEmail(this.email);

			String subject = JSFUtil.getI18N("msg", "register.mail.subject");
			String body = JSFUtil.getI18N("msg", "register.mail.body");

			JSFUtil.getBean(UserServiceImpl.ID, UserService.class).register(
					usuario, subject, body);

			this.username = null;
			this.name = null;
			this.firstSurname = null;
			this.secondSurname = null;
			this.email = null;

			JSFUtil.addGlobalMessage("msg", "register.success",
					FacesMessage.SEVERITY_INFO);

			return MenuOption.HOME.outcome();

		} catch (Throwable e) {
			log.error("Error al registrarse en la aplicacion", e);
			JSFUtil.addGlobalMessage("msg", "register.error",
					FacesMessage.SEVERITY_ERROR);
			return null;
		}

	}
}